package com.lovar.gaming.controller;

import cn.dev33.satoken.annotation.SaIgnore;
import cn.dev33.satoken.context.SaHolder;
import cn.dev33.satoken.stp.SaLoginModel;
import cn.dev33.satoken.stp.StpUtil;
import cn.hutool.core.thread.ThreadUtil;
import cn.hutool.core.util.StrUtil;
import com.lovar.gaming.core.domain.R;
import com.lovar.gaming.core.enums.SysMessageCode;
import com.lovar.gaming.domian.bo.LoginBo;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.*;

/**
 * 控制层-鉴权相关
 *
 * @author Champagne9
 * @date 2024/3/8
 */
@Slf4j
@RestController
@RequestMapping("/auth")
@RequiredArgsConstructor
public class AuthController {

    record LoginVo(String token) {}
    record User(String nickname, String username, String phonenumber) {}

    @SaIgnore
    @PostMapping("/login")
    public R<LoginVo> login(@RequestBody LoginBo loginBo) {
        String username = loginBo.getUsername();
        String password = loginBo.getPassword();

        if (StrUtil.equals(username, "admin") && StrUtil.equals(password, "123456")) {
            SaLoginModel loginModel = new SaLoginModel();
            loginModel.setExtra("username", "admin");
            loginModel.setExtra("phonenumber", "17689799789");
            loginModel.setExtra("userId", 10000L);
            StpUtil.login(10000, loginModel);
            return R.ok(new LoginVo(StpUtil.getTokenInfo().getTokenValue()));
        }
        return R.fail(SysMessageCode.LOGIN_FAILURE);
    }

    @GetMapping("/info")
    public R<User> info() {
        boolean login = StpUtil.isLogin();

        if (login) {
            var phonenumber = (String) StpUtil.getExtra("phonenumber");
            var userId = SaHolder.getStorage().get("userId");
            log.info("本次会话是否有UserId = {}", userId);
            if (userId == null) {
                userId = StpUtil.getExtra("userId");
                SaHolder.getStorage().set("userId", userId);
            }
            return R.ok(new User("管理员", "admin", phonenumber));
        }
        return R.fail(SysMessageCode.LOGIN_EXPIRE);
    }


}
